﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TorrentService;
using System.Management;
using System.IO;
using MonoTorrent.Client;
using MonoTorrent.Common;

namespace BotTorrent
{
    internal class PrivateIrcMethods
{
    // Methods
    public static TimeSpan GetUptime()
    {
        TimeSpan uptimeTs = new TimeSpan();
        ManagementObjectCollection mngInstance = new ManagementClass("Win32_OperatingSystem").GetInstances();
        foreach (ManagementObject mngObject in mngInstance)
        {
            DateTime lastBootUp = ParseCIMDateTime(mngObject["LastBootUpTime"].ToString());
            if (lastBootUp != DateTime.MinValue)
            {
                uptimeTs = (TimeSpan) (DateTime.Now - lastBootUp);
            }
        }
        return uptimeTs;
    }

    public static List<string> ircLoadTorrent(string[] command, ircbot oIrcBot)
    {
        List<string> retVal = new List<string>();
        string help = "!TORRENT LOAD <URL>";
        if (command.Length == 3)
        {
            Exception e;
            if (!command[2].ToUpper().StartsWith("HTTP://"))
            {
                retVal.Add("Invalid URL, URL must begin with http://");
                return retVal;
            }
            try
            {
                Uri url = new Uri(command[2]);
                if (!Directory.Exists(Path.GetDirectoryName(oIrcBot.Settings.TorrentSettings.torrentsPath)))
                {
                    try
                    {
                        Directory.CreateDirectory(Path.GetDirectoryName(oIrcBot.Settings.TorrentSettings.torrentsPath));
                    }
                    catch (Exception exception1)
                    {
                        e = exception1;
                        retVal.Add("Error creating folder for torrent download location: " + e.Message);
                        return retVal;
                    }
                }
                TorrentManager manager = new TorrentManager(Torrent.Load(url, Path.Combine(oIrcBot.Settings.TorrentSettings.torrentsPath, Path.GetFileName(url.AbsolutePath))), oIrcBot.BTClient.Settings.TorrentSettings.downloadsPath, oIrcBot.BTClient.torrentDefaults);
                oIrcBot.BTClient.Register(manager);
                oIrcBot.BTClient.TorrentList.Add(manager);
                manager.Start();
                retVal.Add("Successfully downloaded and started torrent.");
                return retVal;
            }
            catch (Exception exception2)
            {
                e = exception2;
                retVal.Add("Error loading torrent from URL. Error was: " + e.Message);
                return retVal;
            }
        }
        retVal.Add("Invalid URL Specified");
        retVal.Add(help);
        return retVal;
    }

    public static List<string> ircStartTorrent(string[] command, BitTorrentClient BTClient)
    {
        string help = "!TORRENT START <ID> (if no ID, all torrents will be started)";
        List<string> retVal = new List<string>();
        int torrentCount = BTClient.TorrentList.Count;
        if (torrentCount == 0)
        {
            retVal.Add("No torrents currently loaded");
            return retVal;
        }
        if (command.Length == 3)
        {
            int torrentId;
            if (!int.TryParse(command[2], out torrentId))
            {
                retVal.Add(help);
                retVal.Add("You did not provide a valid numeric ID");
                return retVal;
            }
            if (torrentCount < torrentId)
            {
                retVal.Add("Invalid torrent id specified. For a list of torrents issue !TORRENTLIST");
                return retVal;
            }
            BTClient.TorrentList[torrentId].Start();
            retVal.Add("Successfully started torrent with id " + torrentId.ToString());
            return retVal;
        }
        if (command.Length == 2)
        {
            BTClient.StartAll();
            retVal.Add("No torrent ID specified, starting all unstarted torrents.");
            return retVal;
        }
        retVal.Add(help);
        return retVal;
    }

    public static List<string> ircStopTorrent(string[] command, BitTorrentClient BTClient)
    {
        int torrentId;
        string help = "!TORRENT STOP <ID> <YES|NO> (Yes or no to delete files after)";
        List<string> retVal = new List<string>();
        int torrentCount = BTClient.TorrentList.Count;
        if (torrentCount == 0)
        {
            retVal.Add("No torrents currently loaded");
            return retVal;
        }
        if (!int.TryParse(command[2], out torrentId))
        {
            retVal.Add(help);
            return retVal;
        }
        if (torrentCount < torrentId)
        {
            retVal.Add("Invalid torrent id specified. For a list of torrents issue !TORRENTLIST");
            return retVal;
        }
        if ((command.Length == 4) && command[3].ToUpper().Equals("YES"))
        {
            BTClient.TorrentList[torrentId].Stop();
            BTClient.Unregister(BTClient.TorrentList[torrentId]);
            File.Delete(BTClient.TorrentList[torrentId].Torrent.TorrentPath);
            foreach (TorrentFile file in BTClient.TorrentList[torrentId].Torrent.Files)
            {
                try
                {
                    File.Delete(Path.Combine(BTClient.TorrentList[torrentId].SavePath, file.Path));
                }
                catch (Exception)
                {
                    retVal.Add("There was a problem deleting file: " + file.Path);
                }
            }
            BTClient.TorrentList.RemoveAt(torrentId);
            retVal.Add("Succesfully Unregistered torrent");
            return retVal;
        }
        if ((command.Length == 4) && command[3].ToUpper().Equals("NO"))
        {
            BTClient.TorrentList[torrentId].Stop();
            retVal.Add("Succesfully Stopped torrent");
            return retVal;
        }
        retVal.Add(help);
        return retVal;
    }

    private static DateTime ParseCIMDateTime(string wmiDate)
    {
        DateTime date = DateTime.MinValue;
        if ((wmiDate != null) && (wmiDate.IndexOf('.') != -1))
        {
            string tempDate = wmiDate.Substring(0, wmiDate.IndexOf('.') + 4);
            if (tempDate.Length == 0x12)
            {
                int year = Convert.ToInt32(tempDate.Substring(0, 4));
                int month = Convert.ToInt32(tempDate.Substring(4, 2));
                int day = Convert.ToInt32(tempDate.Substring(6, 2));
                int hour = Convert.ToInt32(tempDate.Substring(8, 2));
                int minute = Convert.ToInt32(tempDate.Substring(10, 2));
                int second = Convert.ToInt32(tempDate.Substring(12, 2));
                int milisecond = Convert.ToInt32(tempDate.Substring(15, 3));
                date = new DateTime(year, month, day, hour, minute, second, milisecond);
            }
        }
        return date;
    }
}



}
